package cmpe451.group7.ourcity.util;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Hibernate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * JSON utilty class for storing commonly used functions
 * 
 * @author RamiGökhan
 * 
 */
public class JSONUtils {

	/**
	 * Prints the result set to the output stream as a JSON object
	 * 
	 * @param entityList
	 * @param writer
	 * @throws JSONException
	 */
	public static <T> void JSONWriter(List<T> entityList, PrintWriter writer)
			throws JSONException {
		Gson gson = new GsonBuilder().setExclusionStrategies(
				new JSONExclusionStrategy()).create();
		JSONObject response = new JSONObject();
		JSONArray objects = new JSONArray();

		if (entityList != null) {

			for (T entity : entityList) {
				if(entity instanceof String){
					objects.put(entity);
					continue;
				}

				Hibernate.initialize(entity);
				String jsonString = gson.toJson(entity);
				JSONObject jsonObject = new JSONObject(jsonString);
				objects.put(jsonObject);
			}
			response.put("data", objects);
			response.put("count", entityList.size());
		} else {
			response.put("data", objects);
			response.put("count", 0);
		}

		response.put("success", 1);
		writer.print(response.toString());

	}

	/**
	 * Prints one entity to JSON response.
	 * 
	 * For convenience, same method with the list argument is used.
	 * 
	 * @param entity
	 * @param writer
	 * @throws JSONException
	 */
	public static <T> void JSONWriter(T entity, PrintWriter writer)
			throws JSONException {
		List<T> list = new ArrayList<T>();
		if (entity != null) {
			list.add(entity);
		}
		JSONWriter(list, writer);
	}
}
